package com.bonc.test.redisdemo.ctrl;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSON;
import com.bonc.test.redisdemo.config.RedisClient;
import com.bonc.test.redisdemo.dao.UserDao;
import com.bonc.test.redisdemo.dao.UserMapper;
import com.bonc.test.redisdemo.entity.User;

@RestController
@RequestMapping("/user")
public class UserController {

	private static final Logger log = LoggerFactory.getLogger(UserController.class);
	
	@Autowired
	private UserDao userDao;
	
//	@Autowired
//	private UserMapper userMapper;
	
	@Autowired
	private RedisClient redisClient;
	
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	
	@RequestMapping(value = { "/flush" })
	@ResponseBody
	public String flush() {
		redisTemplate.execute((RedisCallback<Object>) connection -> {
			connection.flushDb();
			return null;
		});
		log.info("缓存已刷新");
		return "ok";
	}
	
//	@RequestMapping(value="/add")
//	public String add(){
//		int num = userMapper.insert("zhangsan", 16);
//		//num=1表示成功
//		log.info("number is {}" , num);
//		return String.valueOf(num);
//	}
	
	@GetMapping(value = {"/{id}"})
	@Cacheable(value="userCache",key= "'user' + #id" )
	@ResponseBody
    public User user(@PathVariable long id) {
		User u =  userDao.findOne(id);
		log.info("走db查询");
		return u;
    }
	
	@RequestMapping(value = {""}, method = RequestMethod.GET)
	@ResponseBody
	public List<User> list() {
		List<User> dataList = new ArrayList<>();
		Long size = redisClient.getListSize("userList");

		if(size==0){
			log.info("FindAll  走db查询");
			dataList= userDao.findAll();
			if (null != dataList) {
	            for (int i = 0; i < dataList.size(); i++) {
	            	redisClient.setListData("userList", JSON.toJSONString(dataList.get(i)));
	            }
	        }
		}else{
			log.info("FindAll  从redis中获取");
			for (int i = 0; i < size; i++) {
				String json = redisClient.getListData("userList",i);
				User u = JSON.parseObject(json, User.class);  
	            dataList.add(u);
	        }
		}
		return dataList;
	}
	
	@RequestMapping(value = {"/delete/{id}"}, method = RequestMethod.GET)
	@CacheEvict(value = { "userCache","userListCache"}, allEntries = true)  
	@ResponseBody
	public String delete(@PathVariable long id) {
		userDao.delete(id);
		return "success";
	}
	
	@RequestMapping(value = {"/save/{id}"}, method = RequestMethod.GET)
	@CacheEvict(value = { "userCache","userListCache"}, allEntries = true)  
	@ResponseBody
	public String save(@PathVariable long id) {
		List<User> userList = new ArrayList<>();
		User user = new User();
		user.setAge(1);
		user.setInfo("1");
		user.setName("1");
		user.setUpdateTime(String.valueOf(System.currentTimeMillis()));

		User user2 = new User();
		user2.setAge(2);
		user2.setInfo("2");
		user2.setName("2");
		user2.setUpdateTime(String.valueOf(System.currentTimeMillis()));

		userList.add(user);
		userList.add(user2);
		userDao.save(userList);

		for (int i = 0; i < userList.size(); i++) {
			String key = String.valueOf(userList.get(i).getId()) + "_" + userList.get(i).getUpdateTime();
			redisClient.setValue(key, JSON.toJSONString(userList.get(i)));
		}
		return "success";
	}
	
	@RequestMapping(value = {"/update/{id}"}, method = RequestMethod.GET)
	@CachePut(value= "userCache",key= "'user' + #id")
	@ResponseBody
	public User update(@PathVariable long id) {
		User user = userDao.findOne(id);
		user.setAge(10086);
		userDao.save(user);
		Long size = redisClient.getListSize("userList");
		
		for (int j = 0; j < size; j++) {
			User u = JSON.parseObject(redisClient.getListData("userList", j), User.class);  
			if(id==u.getId()){
				redisClient.updateListData("userList", j, JSON.toJSONString(user));
				log.info("已更新缓存");
			}
		}
		
		return user;
	}

}
